package com.whyw.system.security;

import com.whyw.system.service.UserService;
import com.whyw.system.utils.UserContextHolder;
import com.whyw.constant.UserConstant;
import com.whyw.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(UserConstant.LOGIN_FAILED);
        }
        UserContextHolder.setUser(user);
        return org.springframework.security.core.userdetails.User.withUsername(username)
                .password(user.getPassword())
                .username(username)
                .build();
    }
}
